<template>
  <PageWrapper contentBackground>
    <template #title>
      <span>办公用品申购</span>
    </template>
    <CollapseContainer title="基本信息">
      <BasicForm @register="register1"> </BasicForm>
    </CollapseContainer>
    <CollapseContainer title="物品列表">
      <Button type="primary" @click="addTable">新增</Button>
      <span>总价：{{ calculatePrice() }}</span>
      <Form ref="formRef" name="dynamic_form_item" :model="data" :label-col="{ span: 10 }">
        <CreateItem
          @deleteTable="deleteTable"
          :order="i"
          v-for="(item, i) in formList"
          :form="item"
          :key="i"
        />
      </Form>
    </CollapseContainer>
    <div class="footer">
      <Button @click="resetSubmit()">重置</Button>
      <Button type="primary" style="margin-left: 10px" @click="handleSubmit()">提交</Button>
    </div>
  </PageWrapper>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs, ref, h, onMounted } from 'vue';
import { BasicForm, useForm } from '/@/components/Form/index';
import { CollapseContainer } from '/@/components/Container/index';
import { Input, Form, message } from 'ant-design-vue';
import { PageWrapper } from '/@/components/Page';
import { Button } from '/@/components/Button';
import { useUserStore } from '/@/store/modules/user';
import { deptSimple, userSimple } from '/@/api/backs/foundation/foundation';
import { officeAdd } from '/@/api/backs/workFlow/operation';
import { useTabs } from '/@/hooks/web/useTabs';
import { useGo } from '/@/hooks/web/usePage';


import moment from 'moment';
import CreateItem from '../components/CreateItem.vue';
export default defineComponent({
  components: {
    BasicForm,
    CollapseContainer,
    PageWrapper,
    [Input.name]: Input,
    Button,
    Form,
    CreateItem,
  },
  setup() {
    const go = useGo();
    const { closeCurrent } = useTabs();
    const userStore = useUserStore();
    const data: any = reactive({
      formList: [
        {
          officeListName: '',
          listNumber: '',
          unit: '',
          price: '',
          purchaseDate: '',
          url: [],
          reason: '',
          allPrice: 0,
        },
      ],
    });
    const formRef = ref(null);
    const addTable = () => {
      data.formList.push({
        officeListName: '',
        listNumber: '',
        unit: '',
        price: '',
        purchaseDate: '',
        url: [],
        reason: '',
        allPrice: 0,
      });
    };
    const deleteTable = (key) => {
      data.formList.splice(key, 1);
    };
    const [register1, { validate: validate1 }] = useForm({
      schemas: [
        {
          field: 'number',
          component: 'InputNumber',
          label: '编号',
          colProps: {
            span: 8,
          },
        },
        {
          field: 'deptAll',
          label: '申请部门',
          component: 'ApiTreeSelect',
          componentProps: {
            placeholder: '请选择指定部门',
            api: deptSimple,
            labelField: 'name',
            valueField: 'id',
            labelInValue: true,
            dropdownStyle: { maxHeight: '400px', overflow: 'auto' },
            replaceFields: {
              children: 'children',
              title: 'name',
              key: 'id',
              value: 'id',
            },
          },
          colProps: {
            span: 8,
          },
        },
        {
          field: 'userAll',
          component: 'ApiSelect',
          label: '申请人',
          componentProps: {
            api: userSimple,
            labelField: 'nickname',
            valueField: 'id',
            labelInValue: true,
          },
          colProps: {
            span: 8,
          },
        },
        {
          field: 'reason',
          component: 'InputTextArea',
          label: '申购原因',
          colProps: {
            span: 8,
          },
          required: true,
        },
        {
          field: 'place',
          component: 'Select',
          label: '办公地点',
          componentProps: {
            options: [
              { value: '成都温江', label: '成都温江' },
              { value: '湖南长沙', label: '湖南长沙' },
              { value: '成都武侯', label: '成都武侯' },
            ],
          },
          colProps: {
            span: 8,
          },
          required: true,
        },
      ],
      labelWidth: 80,
      actionColOptions: { span: 24 },
      showResetButton: false,
      showSubmitButton: false,
    });
    onMounted(() => {});
    function calculatePrice() {
      let num = 0;
      if (data.formList && data.formList.length) {
        data.formList.forEach((item) => {
          if (item.price && item.listNumber) {
            item.allPrice = item.price * item.listNumber;
            num += item.allPrice;
          }
        });
        return num;
      }
    }
    async function handleSubmit() {
      try {
        let params = {};
        const data1 = await validate1();
        formRef.value.validateFields().then(async () => {
          params = data1;
          let listData = JSON.parse(JSON.stringify(data.formList));
          if (listData && listData.length) {
            listData.forEach((i) => {
              i.url = i.url[0];
            });
          }
          params = {
            list: listData,
            number: data1.number,
            userName: data1.userAll ? data1.userAll.label : null,
            userId: data1.userAll ? data1.userAll.value : null,
            deptId: data1.deptAll ? data1.deptAll.value : null,
            deptName: data1.deptAll ? data1.deptAll.label : null,
            reason: data1.reason,
            place: data1.place,
            allPrice: calculatePrice(),
          };
          // message.success('success');
          console.log(params);
          // return;
          try {
            await officeAdd(params);
            message.success('发起成功');
            go('/workFlowManage/operationFlow/officeSubscript');
            closeCurrent();
          } catch (error) {}

          console.log(params);
        });

        // console.log(params);
      } catch (e) {
        console.log(e);
      }
    }

    return {
      data,
      ...toRefs(data),
      moment,
      register1,
      handleSubmit,
      addTable,
      deleteTable,
      formRef,
      calculatePrice,
    };
  },
});
</script>
<style lang="less" scoped>
.footer {
  display: flex;
  justify-content: center;
  margin: 10px;
}
</style>
